/**
 * @FileName: pthread_cond_timedwait.cc
 * @Author: 李波(Edwin Lee)
 * @Date: 2024-04-18 14:07:14
 * @Version: 1.0
 * @Description:测试pthread_cond_timedwait()函数在超时后是否会抢锁,结果是会抢锁的 
 */

#include <unistd.h>
#include <cstdio>
#include <pthread.h>
#include <sys/time.h>
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;      // 初始化条件变量。
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;   // 初始化互斥锁
void* thfun(void* arg);
int main()
{
	pthread_t pid;
	pthread_create(&pid, NULL, thfun, NULL);
	sleep(5);
	pthread_mutex_lock(&mutex);
	printf("主函数抢到锁\n");
	pthread_mutex_unlock(&mutex);
	printf("主函数以释放锁\n");
	sleep(30);
	return 0;
}

void* thfun(void* arg)
{
	struct timeval now;
	struct timespec outtime;
	gettimeofday(&now,NULL);
	outtime.tv_sec=now.tv_sec+2;
	outtime.tv_nsec=now.tv_usec;
	pthread_mutex_lock(&mutex);
	
	printf("线程抢到锁\n");
	pthread_cond_timedwait(&cond,&mutex,&outtime);
	printf("等待超时,sleep 30\n");
	sleep(30);
	printf("sleep 结束\n");
	pthread_mutex_unlock(&mutex);
	return nullptr;
}


